# -*- coding: UTF-8 -*-
import os
import random


def get_base_path():
    return os.path.dirname(os.path.dirname(os.path.realpath(os.path.dirname(__file__))))


def get_meta_path():
    return os.path.join(get_base_path(), "meta")


def hex2hanzi(hex_string):
    unicode_hanzi = ''  # 定义一个空字符串
    for i in range(len(hex_string) / 4):  # 因为Unicode是4个字符表示一个汉字，每四个一组
        hex_char = hex_string[i * 4: i * 4 + 4]
        if hex_char == '0000':
            hex_char = '0040'
        if hex_char == '007f':
            hex_char = '00e0'
        unicode_char = "\\u" + hex_char
        unicode_hanzi = unicode_hanzi + unicode_char
    return unicode_hanzi.decode('unicode_escape')


def generate_random_string(length):
    """Generate a random string of given length."""
    letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    return ''.join(random.choice(letters) for _ in range(length))


def ascii2hex(s):
    if not isinstance(s, str):
        s = s.decode('utf-8')
    result = ''
    for c in s:
        tmp = repr(c).replace("u'", "", 1).replace("\\u", '').replace("\\x", '00').replace("'", '')
        if len(tmp) == 1:
            result += hex(ord(c)).replace('0x', '')
        elif ord(c) < 16:
            result += '0' + hex(ord(c)).replace('0x', '')
        else:
            result += tmp
    return result
